<?php

namespace app\models;

use \app\components\BaseActiveRecord;
use app\extensions\rongcloud\RongCloudService;
use app\helpers\AppHelper;
use Yii;

/**
 * This is the model class for table "ii_sms".
 *
 * @property integer $id
 * @property integer $code
 * @property string $content
 * @property string $phone
 * @property integer $ip
 * @property integer $ctime
 * @property integer $status
 */
class Sms extends BaseActiveRecord {

    const SAFE_PHONE = 13812345678;

    const VERIFY_NUM = 5;
    const MAX_IP_NUM = 10;
    const expire_time = 600;

    const TEMPLATE_BASE = '0xGNiE7WQTIafc6DdOyik0';
    const TEMPLATE_WITHDRAW_DONE = 'c_-uAOrtAhra9Aph5qHZ9_';

    /**
     * @inheritdoc
     */
    public static function tableName() {
        return 'ii_sms';
    }

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['code', 'ip', 'ctime', 'status'], 'integer'],
            [['content'], 'string', 'max' => 200],
            [['phone'], 'string', 'max' => 11],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'code' => 'Code',
            'content' => 'Content',
            'phone' => 'Phone',
            'ip' => 'Ip',
            'ctime' => 'Ctime',
            'status' => 'Status',
        ];
    }

    public function send($phone, $templateId, $params = []) {
        if (!AppHelper::isValid($phone)) {
            return static::retErr('手机号码不合法');
        }

        if (YII_ENV_PROD) {
            $res = $this->canSend($phone);
            if (!$this->isOk($res)) {
                return $res;
            }
        }

        $verify_code = $this->genCode(5);
        if (YII_ENV_DEV) {
            return $this->saveResult($phone, '', $verify_code);
        }

        $minute = self::expire_time / 60;

        if(empty($params)){
            $params = ['p1' => $verify_code, 'p2' => $minute];
        }
        $res = RongCloudService::smsSend($phone, $templateId, $params);
        if (!$this->isOk($res)) {
            return $res;
        }

        $content = $res['data'];
        return $this->saveResult($phone, print_r($content, TRUE), $verify_code);
    }

    protected function saveResult($phone, $content, $verify_code) {
        $model = new Sms();
        $model->phone = $phone;
        $model->content = $content;
        $model->code = $verify_code;
        $model->ip = AppHelper::getClientIp();
        $model->ctime = time();
        $model->status = static::STATUS_NO;
        $res = $model->save();
        if ($res['code'] != 0) {
            return $res;
        }
        if (!YII_ENV_PROD) {
            $res['data']['code'] = $model->code;
        }
        return $res;
    }

    protected function canSend($phone) {
        $zero_time = strtotime(date("Y-m-d"));
        $ip = AppHelper::getClientIp();
        $count = static::find()->where(['ip' => $ip])->andWhere(['>', 'ctime', $zero_time])->count();
        if ($count > self::MAX_IP_NUM) {
            return static::retErr('收不到验证短信？换个网络环境试试哦~如果你是土豪，那就关闭wifi，开启流量再注册吧！');
        }

        $models = static::find()->where(['phone' => $phone])->andWhere(['>', 'ctime', $zero_time])->orderBy('ctime desc')->asArray()->all();
        if (!empty($models)) {
            if (count($models) > self::VERIFY_NUM) {
                return static::retErr('一个手机号一天最多能发送' . self::VERIFY_NUM . '次验证码');
            }

            $msg_send_ret = current($models);
            if ($msg_send_ret['ctime'] + 60 > time()) {
                return static::retErr('操作太频繁，一分钟内只能发送一次验证码');
            }
        }
        return self::retOK();
    }

    public function verify($phone, $verify_code) {
        if (!AppHelper::isValid($phone)) {
            return static::retErr('手机号码不合法');
        }

        $key = "{$phone}_verify_fail_num";
        $verify_fail_num = Yii::$app->cache->get($key);
        if ($verify_fail_num >= self::VERIFY_NUM) {
            return self::retErr('验证码错误次数过多,请30分钟后在试');
        }

        if ($phone == self::SAFE_PHONE && $verify_code == 12345) {
            return static::retOK();
        }

        /* @var $model Sms */
        $model = static::find()
            ->where(['phone' => $phone, 'code' => $verify_code, 'status' => static::STATUS_NO])
            ->orderBy('id desc')->one();
        if (!$model || $model->ctime + static::expire_time < time()) {
            $verify_fail_num = $verify_fail_num ? ($verify_fail_num + 1) : 1;
            Yii::$app->cache->set($key, $verify_fail_num, 3600);
            return self::retErr('验证码不正确或者已过期');
        }

        Yii::$app->cache->delete($key);

        $model->status = static::STATUS_YES;
        return $model->save();
    }

    protected function genCode($len = 5) {
        $str = '';
        for ($i = 0; $i < $len; $i++) {
            $str .= mt_rand(1, 9);
        }
        return $str;
    }

}
